﻿/**************************************************
* 版权所有:Copyright (C) 
* 作    者:蔡海翔
* 创建日期:2014/6/16 17:17:14
* 描    述:
* 修改日期:
* 修改内容:
****************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataEntity;
using DataAccess;
using System.Web;
using System.Web.Security;
namespace Tools
{
    public class UserLogin
    {
        DataContext db = new DataContext();
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public  string Login(string userName, string passWord)
        {
            
            var Encrypt = new Encrypt();
            passWord = Encrypt.Encode(passWord);
            //password = Common.ToMD5(password);
            if (!db.SysUsers.Any(u => u.UserName == userName && u.Password == passWord))
            {
                if (!db.SysUsers.Any(u => u.UserName == userName))
                {
                    //用户名不存在
                    //Common.WriteLog(0, "错误用户名:" + username, SystemLogType.用户名错误);
                    return "-1";
                }
                else
                {
                    //用户名存在，密码不正确
                    //Common.WriteLog(r1.First().UserID, "错误密码:" + password, SystemLogType.登录密码错误);
                    return "-2";
                }
            }
            else
            {
                var user = db.SysUsers.Where(u => u.UserName == userName && u.Password == passWord).FirstOrDefault();
                if (user.BeLock == true)
                {
                    //该账号被停用
                    return "-3";
                }
                else
                //{
                //    //正常登录
                //    //Common.WriteLog(r.First().UserID, "", SystemLogType.登录系统);
                //    //保存用户信息
                //    CreateUserInfoFormDataBase(username);
                //    return "0";
                //}
                {
                    SaveUserInfo(userName);
                    return "0";
                }
            }
        }


        public static void SaveUserInfo(string userName)
        {
            DataContext db = new DataContext();
            var r = db.SysUsers.First(u => u.UserName == userName);

            //cookies用来保存用户名，避免下次登录还要输用户名

            HttpContext.Current.Response.Cookies["UserName"].Value = r.UserName;
            HttpContext.Current.Response.Cookies["UserName"].Expires = DateTime.Now.AddYears(50);
            //HttpContext.Current.Response.Cookies["SysRoleID"].Value = r.SysRoleID.ToString();
            //HttpContext.Current.Response.Cookies["SysRoleID"].Expires = DateTime.Now.AddYears(50);
            HttpContext.Current.Response.Cookies["IsAdmin"].Value = r.IsAdmin.ToString();
            HttpContext.Current.Response.Cookies["IsAdmin"].Expires = DateTime.Now.AddYears(50);
            //FormsAuthentication.SetAuthCookie(r.SysRoleID.ToString(), false);//true表示保留持久cookie，过期时间就是web.config里的时间，如果是false则关闭浏览器就过期
            //session用来保存当前登录用户信息，以供其他模块使用
            HttpContext.Current.Session["userinfo"] = r;
            HttpContext.Current.Session.Timeout = 600;

        }
        /// <summary>
        /// 查询当前用户有权限访问的菜单和模块(若无浏览权限，则不显示该菜单)
        /// </summary>
        /// <returns></returns>
        public static List<SysMenu> GetLimitedMenu()
        {
            string userno = string.Empty;
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Cookies["UserName"].Value))
            {

                userno = HttpContext.Current.Request.Cookies["UserName"].Value;

            }

            DataContext db = new DataContext();
            if (string.IsNullOrEmpty(userno))
            {
                return null;
            }


            var menu = db.SysMenus.Where(m => m.BeLock == false).ToList();

            var user = db.SysUsers.First(u => u.UserName== userno);

            //如果是超级管理员，返回所有可用菜单
            if (user.IsAdmin)
            {
                //找到不重复的父级ID 
                List<int> m_parentid = menu.Select(s => s.ParentID).Distinct().ToList();

                //去掉没有子集的菜单
                List<SysMenu> m_result = menu.Where(m => m_parentid.Contains(m.ParentID)).ToList();
                return m_result;
            }

            var role = db.SysRoleRights.Where(n => n.SysRoleID == user.SysRoleID).ToList();


            //不存在用户权限，则去判断用户所属的角色的角色权限
            //判断是否有角色权限
            if (role.Count() != 0)
            {
                List<int> menuid = new List<int>();
                foreach (var m in role)
                {
                    var p_menu = menu.Find(o => o.ID == m.SysMenuID);
                    if (p_menu == null)
                    {
                        continue;
                    }
                    if (!menuid.Contains(p_menu.ID))
                    {
                        menuid.Add(p_menu.ID);
                    }
                    do
                    {
                        p_menu = menu.Find(o => o.ID == p_menu.ParentID);
                        if (!menuid.Contains(p_menu.ID))
                        {
                            menuid.Add(p_menu.ID);
                        }
                    }
                    while (p_menu.ParentID != 0);
                }

                List<SysMenu> m_result = menu.Where(m => menuid.Contains(m.ID)).ToList();
                return m_result;
            }
            else
            {
                //定义一个空集
                List<SysMenu> m_result = menu.Where(m => m.ID == -1).ToList();
                return m_result;
            }

        }
        /// <summary>
        /// 保存用户详细信息
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public static SysUser CreateUserInfo()
        {
            string userName = string.Empty;
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Cookies["UserName"].Value))
            {
                userName = HttpContext.Current.Request.Cookies["UserName"].Value;
            }
            if (string.IsNullOrEmpty(userName))
            {
                return null;
            }
            else
            {
                DataContext db = new DataContext();
                var user = db.SysUsers.First(u => u.UserName == userName);
                return user;
            }
        }
    }
}
